﻿using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Web.Mvc;
using Hx.DataTransferObject;

namespace Hx.WebSite.Controllers
{
    public class HomeController : BaseController
    {
        public ActionResult Index()
        {
            var sp = new Stopwatch();
            sp.Start();
            var result = _categoriyImpl.AllCategories();
            sp.Stop();
            Debug.WriteLine(sp.ElapsedMilliseconds);
            var topCategories = result.Where(n => !n.ParentId.HasValue);
            foreach (var category in topCategories)
                category.Children = GetChildren(result, category);

            ViewBag.Categorys = topCategories;
            return View();
        }

        private List<CategoryObject> GetChildren(List<CategoryObject> allCategory, CategoryObject parent)
        {
            var result = new List<CategoryObject>();
            foreach (var category in allCategory.Where(category => parent.Id == category.ParentId))
            {
                result.Add(category);
                category.Children = GetChildren(allCategory, category);
            }
            return result;
        }
    }
}